'use client'
const isBrowser = () => typeof window !== 'undefined';
/**
 * 网络请求配置
 */
import axios from "axios";
import Cookies from "js-cookie";
// import { error, warning } from "../components/Dialog";
import { getToken } from "../api/auth";

let reGetTokenFlag401 = false;
/* 是否有请求正在刷新token的标志 */
if(isBrowser()){
  window.isRefreshing = false;
}
/* 被挂起的请求数组 */
let refreshSubscribers = [];

/* push所有请求到数组中 */
function subscribeTokenRefresh(cb) {
  refreshSubscribers.push(cb);
}
/* 刷新请求（refreshSubscribers数组中的请求得到新的token之后会自执行，用新的token去请求数据） */
function onRrefreshed() {
  refreshSubscribers.map((cb) => cb());
}

function request(options) {
  const instance = axios.create({
    timeout: 20000, // 设置超时时间20s
    withCredentials: true // 允许携带cookie
    // baseURL: "/megrez"
  });

  /**
 * http request 拦截器
 */
  instance.interceptors.request.use(
    async (config) => {
      if (config.url !== "/api/v1/auth/login") {
        // 获取token的接口不进行拦截
        if (Cookies.get("accessToken") === undefined) {
          // cookie中没有token的时候才拦截
          if (!window.isRefreshing) {
            // 当没有请求正在刷新或者获取token的时候，进行标记，将获取token过程中发起的请求存储在数组中，拿到token后再发送
            window.isRefreshing = true;
            getToken().then(() => {
              // 获取到token后将被挂起的请求释放
              onRrefreshed();
              /* 执行onRefreshed函数后清空数组中保存的请求 */
              refreshSubscribers = [];
              window.isRefreshing = false;
            }).catch((err) => {
              console.log(err);
            });
          }
          /**
         * 将获取token过程中发起的请求存储在数组
         */
          const retry = new Promise((resolve) => {
            /* (token) => {...}这个函数就是回调函数 */
            subscribeTokenRefresh(() => {
              /* 将请求挂起 */
              config.headers.Authorization = "Bearer" + " " + Cookies.get("accessToken");
              resolve(config);
            });
          });
          return retry;
        }
        config.headers.Authorization = "Bearer" + " " + Cookies.get("accessToken");

        return config;
      }
      return config;
    },
    (err) => Promise.reject(err)
  );

  return new Promise((resolve, reject) => {
    instance({ ...options, instance })
      .then((response) => {
        console.log("response", response);

        if (response.status !== 200) {
          resolve();
          throw response;
        } else if (response.data) {
          resolve(response.data);
        }
      }).catch((err) => {
        console.log("err", err);
        if (err.response.status === 401) {
          console.log("pppppppppp");
          try {
            if (!reGetTokenFlag401) {
              reGetTokenFlag401 = true;

              getToken().then(res => {
                reGetTokenFlag401 = false;
                window.location.reload();
              })
            }

          } catch (error) {
            console.log(error);
          }
        }
        // 统一处理请求错误 
        if (err.mes !== undefined) {
          // error({
          //   content: <div>{`${err.message}`}</div>
          // });
        }
        // 后端的错误处理
        if (err && err.data) {
          let content = err.data.message;
          if (err.data.data !== null) {
            content += `：${err.data.data}`;
          }
          // error({
          //   content: <div>{content}</div>
          // });
        }
      });
  });
}
export function get(url, params) {
  return request({
    method: 'get',
    url,
    params
  });
}

export function post(url, data) {
  return request({
    method: 'post',
    url,
    data
  });
}
export function put(url, params) {
  return request({
    method: 'put',
    url,
    params
  });
}
export function del(url, params) {
  return request({
    method: 'delete',
    url,
    params
  });
}
export default request;
